<template>
  <div class="organization-module">
    <!-- 第一行 -->
    <div class="top-sections">
      <!-- 组织列表 -->
      <el-card class="section organization-section">
        <template #header>
          <h2 style="display: inline-flex; align-items: center">
            组织列表
            <el-tooltip content="这是你的组织，鼠标悬浮在组织名称上可查看组织详情" placement="right">
              <el-icon style="vertical-align: middle; margin-left: 8px">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </h2>
        </template>
        <!-- 新增组织 -->
        <el-button type="primary" size="small" @click="addOrgDialog">新增组织</el-button>
        <el-table
          :data="organizations"
          class="organization-table"
          height="250"
          max-height="250"
          :default-sort="{ prop: 'created_at', order: 'descending' }"
        >
          <el-table-column label="序号" width="80" align="center" header-align="center" sortable>
            <template #default="{ row, $index }">
              <span>{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="org_name" label="组织名称" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              <el-popover placement="right" width="auto" trigger="hover">
                <template #reference>
                  <span>{{ row.org_name }}</span>
                </template>
                <div class="popover-content">
                  <p><span class="label">组织ID:</span> {{ row.org_id }}</p>
                  <p><span class="label">组织名称:</span> {{ row.org_name }}</p>
                  <p><span class="label">描述:</span> {{ row.description }}</p>
                  <p><span class="label">创建时间:</span> {{ row.created_at }}</p>
                  <p><span class="label">组织所在学年:</span> {{ row.course_year }}</p>
                  <p><span class="label">组织所在学期:</span> {{ row.course_term }}</p>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" width="auto" align="center" header-align="center" sortable />
          <el-table-column
            prop="created_at"
            label="创建时间"
            width="auto"
            align="center"
            header-align="center"
            sortable
          />
          <el-table-column prop="org_id" label="组织ID" width="auto" align="center" header-align="center" sortable />
          <el-table-column label="操作" width="auto" align="center" header-align="center">
            <template #default="{ row }">
              <el-button type="info" size="small" @click="viewOrganization(row.org_id)">查看</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-container">
              <el-icon :size="50" color="#909399" :class="{ 'spin-icon': isOrgLoading }" v-if="isOrgLoading"
                ><Loading v-if="isOrgLoading"
              /></el-icon>
              <p>{{ isOrgLoading ? "加载中..." : `暂无组织` }}</p>
            </div>
          </template>
        </el-table>
        <el-pagination
          :total="organizations.length"
          :page-size="organizations.length"
          layout="total"
          style="text-align: right; margin-top: 10px"
        />
      </el-card>
      <!-- 消息列表 -->
      <el-card class="section notice-section">
        <template #header>
          <h2 style="display: inline-flex; align-items: center">
            通知列表
            <el-tooltip content="这是你的通知，鼠标悬浮在学号上可查看成员详情" placement="right">
              <el-icon style="vertical-align: middle; margin-left: 8px">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </h2>
        </template>
        <!-- 待处理/已处理/结果 -->
        <el-radio-group
          v-model="msgStatus"
          class="msg-status"
          size="small"
          @change="handleMsgStatusChange"
          :disabled="isMsgLoading"
        >
          <el-radio-button label="待处理" :value="待处理"></el-radio-button>
          <el-radio-button label="已处理" :value="已处理"></el-radio-button>
          <el-radio-button label="未回应" :value="未回应"></el-radio-button>
        </el-radio-group>
        <template v-if="msgStatus === '待处理'">
          <!-- 全部同意 -->
          <el-button
            type="success"
            size="small"
            @click="setAllMsgStatus('approved')"
            :disabled="!isAnyMsgSelected || msgStatus !== '待处理' || isMsgLoading"
            >全部同意</el-button
          >
          <!-- 全部拒绝 -->
          <el-button
            type="danger"
            size="small"
            @click="setAllMsgStatus('rejected')"
            :disabled="!isAnyMsgSelected || msgStatus !== '待处理' || isMsgLoading"
            >全部拒绝</el-button
          >
        </template>
        <template v-else-if="msgStatus === '未回应'">
          <!-- 全部撤回 -->
          <el-button type="info" size="small" @click="withdrawAll" :disabled="!isAnyMsgSelected || isMsgLoading"
            >全部撤回</el-button
          >
        </template>
        <el-table
          :data="showMsgs"
          class="member-table"
          height="250"
          max-height="250"
          :default-sort="{ prop: 'updatetime', order: 'descending' }"
          @selection-change="handleMsgSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center" header-align="center" sortable>
            <template #default="{ row, $index }">
              <span>{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="user.username" label="学号" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              <el-popover placement="right" width="auto" trigger="hover">
                <template #reference>
                  <span>{{ row.user.username }}</span>
                </template>
                <div class="popover-content">
                  <p><span class="label">学号:</span> {{ row.user.username }}</p>
                  <p>
                    <span class="label">姓名:</span>
                    {{ row.personal_info == null ? "-" : row.personal_info.name }}
                  </p>
                  <p>
                    <span class="label">专业:</span>
                    {{ row.personal_info == null ? "-" : row.personal_info.major }}
                  </p>
                  <p><span class="label">邮箱:</span> {{ row.user.email }}</p>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="personal_info.name"
            label="姓名"
            width="auto"
            align="center"
            header-align="center"
            sortable
          />
          <el-table-column prop="updatetime" label="时间" width="auto" align="center" header-align="center" sortable />
          <el-table-column prop="type" label="方向" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              <el-tag :type="row.type === '我邀请Ta加入我' ? 'success' : 'warning'" class="status-tag">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="org_name" label="组织名称" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              <el-popover placement="right" width="auto" trigger="hover">
                <template #reference>
                  <span>{{ row.org_name }}</span>
                </template>
                <div class="popover-content">
                  <p><span class="label">组织ID:</span> {{ row.org_info.org_id }}</p>
                  <p><span class="label">组织名称:</span> {{ row.org_info.org_name }}</p>
                  <p><span class="label">描述:</span> {{ row.org_info.description }}</p>
                  <p><span class="label">创建时间:</span> {{ row.org_info.created_at }}</p>
                  <p><span class="label">组织所在学年:</span> {{ row.org_info.course_year }}</p>
                  <p><span class="label">组织所在学期:</span> {{ row.org_info.course_term }}</p>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              <el-tag :type="row.status === 'approved' ? 'success' : row.status === 'pending' ? 'warning' : 'danger'">
                {{ row.status === "approved" ? "已同意" : row.status === "pending" ? "未处理" : "已拒绝" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="auto"
            align="center"
            header-align="center"
            sortable
            v-if="msgStatus !== '已处理'"
          >
            <template #default="{ row }">
              <template v-if="msgStatus === '待处理'">
                <el-button type="primary" size="small" @click="setMsgStatus(row, 'approved')">同意</el-button>
                <el-button type="danger" size="small" @click="setMsgStatus(row, 'rejected')">拒绝</el-button>
              </template>
              <template v-else>
                <el-button type="info" size="small" @click="withdraw(row)">撤回</el-button>
              </template>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty-container">
              <el-icon v-if="isMsgLoading" :size="50" color="#909399" :class="{ 'spin-icon': isMsgLoading }">
                <Loading />
              </el-icon>
              <p>{{ isMsgLoading ? "加载中..." : `暂无 ${msgStatus} 的消息` }}</p>
            </div>
          </template>
        </el-table>
        <el-pagination
          :total="showMsgs.length"
          :page-size="showMsgs.length"
          layout="total"
          style="text-align: right; margin-top: 10px"
        />
      </el-card>
    </div>
    <!-- 搜索 -->
    <el-card class="section search-section">
      <template #header>
        <h2 style="display: inline-flex; align-items: center">
          搜索
          <el-tooltip content="搜索成员或组织，多个请用英文逗号分隔，然后邀请或加入Ta" placement="right">
            <el-icon style="vertical-align: middle; margin-left: 8px">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </h2>
      </template>
      <div class="search-controls">
        <el-input
          placeholder="请输入搜索内容 多个请用英文逗号分隔"
          v-model="searchQuery"
          class="search-input"
          :disabled="isSearchLoading"
          :loading="isSearchLoading"
          clearable
          @keyup.enter="performSearch"
        />
        <el-radio-group v-model="searchType" class="search-type">
          <el-radio-button label="member">
            <el-icon style="vertical-align: middle"><User /></el-icon> 成员
          </el-radio-button>
          <el-radio-button label="organization">
            <el-icon style="vertical-align: middle"><OfficeBuilding /></el-icon> 组织
          </el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="performSearch">
          <el-icon style="vertical-align: middle"><Search /></el-icon> 搜索
        </el-button>
      </div>
      <div class="search-actions" style="margin-top: 10px">
        <el-button type="primary" size="small" @click="inviteOrApplyAll" :disabled="!isAnySearchSelected">
          全部{{ searchType === "member" ? "邀请" : "申请" }}
        </el-button>
        <el-label v-if="searchResults.length > 0" style="font-size: 12px; margin-left: 10px"
          >{{ searchType === "member" ? "成员学号" : "组织ID" }}:
          {{ searchType === "member" ? searchMemberKeywords : searchOrgKeywords }}</el-label
        >
      </div>
      <el-table
        :data="searchResults"
        class="search-table"
        height="250"
        max-height="250"
        :default-sort="{ prop: 'created_at', order: 'descending' }"
        @selection-change="handleSearchSelectionChange"
      >
        <el-table-column type="selection" width="auto" :selectable="isRowSelectable" />
        <el-table-column label="序号" width="80" align="center" header-align="center" sortable>
          <template #default="{ row, $index }">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>

        <!-- 根据 searchType 显示不同的表头 -->
        <template v-if="searchType === 'organization'">
          <el-table-column prop="org_id" label="组织ID" width="auto" align="center" header-align="center" sortable />
          <el-table-column
            prop="org_name"
            label="组织名称"
            width="auto"
            align="center"
            header-align="center"
            sortable
          />
          <el-table-column prop="description" label="描述" width="auto" align="center" header-align="center" sortable />
          <el-table-column prop="created_by" label="创建者" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              {{ row.created_by === local_student_id ? "我的组织" : row.created_by }}
            </template>
          </el-table-column>
          <el-table-column
            prop="course_year"
            label="组织学年"
            width="auto"
            align="center"
            header-align="center"
            sortable
          />
          <el-table-column
            prop="course_term"
            label="组织学期"
            width="auto"
            align="center"
            header-align="center"
            sortable
          />
        </template>

        <template v-else-if="searchType === 'member'">
          <el-table-column prop="user_id" label="用户ID" width="auto" align="center" header-align="center" sortable />
          <el-table-column prop="username" label="学号" width="auto" align="center" header-align="center" sortable>
            <template #default="{ row }">
              {{ row.username === local_student_id ? "我" : row.username }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="auto" align="center" header-align="center" sortable />
        </template>

        <el-table-column label="操作" width="auto" align="center" header-align="center" sortable>
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="inviteOrApply(row)"
              :disabled="
                (searchType === 'organization' &&
                  (row.created_by === local_student_id ||
                    appliedOrgIds.includes(row.org_id) ||
                    invitedOrgIds.includes(row.org_id))) ||
                (searchType === 'member' && row.username === local_student_id)
              "
            >
              {{
                searchType === "member"
                  ? row.username === local_student_id
                    ? "我"
                    : "邀请"
                  : row.created_by === local_student_id
                  ? "我的组织"
                  : appliedOrgIds.includes(row.org_id)
                  ? "已申请/已同意"
                  : invitedOrgIds.includes(row.org_id)
                  ? "已邀请/已同意"
                  : "申请"
              }}
            </el-button>
          </template>
        </el-table-column>
        <!-- 空状态 -->
        <template #empty>
          <div class="empty-container">
            <el-icon v-if="isSearchLoading" :size="50" color="#909399" :class="{ 'spin-icon': isSearchLoading }"
              ><Loading
            /></el-icon>
            <p>{{ isSearchLoading ? "搜索中..." : "暂无数据" }}</p>
          </div>
        </template>
      </el-table>
      <el-pagination
        :total="searchResults.length"
        :page-size="searchResults.length"
        layout="total"
        style="text-align: right; margin-top: 10px"
      />
    </el-card>

    <!-- 新增组织对话框 -->
    <el-dialog title="新增组织" v-model="dialogVisible" width="30%" align-center="true">
      <el-form label-width="auto" style="padding: 0 20px">
        <el-form-item label="组织名称">
          <el-input v-model="organizationName" placeholder="请输入组织名称"></el-input>
        </el-form-item>

        <el-form-item label="组织描述">
          <el-input v-model="organizationDescription" placeholder="请输入组织描述"></el-input>
        </el-form-item>

        <el-form-item label="组织学年">
          <el-radio-group v-model="organizationYear" size="small">
            <el-radio-button v-for="year in years" :key="year" :label="year">
              {{ year }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="组织学期">
          <el-radio-group v-model="organizationTerm" size="small">
            <el-radio-button label="第一学期"></el-radio-button>
            <el-radio-button label="第二学期"></el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrganization">确认</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 邀请成员弹出框 -->
    <el-dialog
      v-model="inviteMemberDialogVisible"
      :title="`邀请 ${currentInviteMember?.map(member => `【${member.username}】`).join(',')} 到组织`"
      width="50%"
      align-center="true"
    >
      <el-form>
        <el-form-item label="选择组织">
          <el-table :data="org_invite_list" @selection-change="handleInviteOrgSelectionChange" height="250">
            <el-table-column type="selection" width="55" align="center" :selectable="isOrgSelectable" />
            <el-table-column prop="username" label="被邀请人" align="center" />
            <el-table-column prop="org_name" label="组织名称" align="center" />
            <el-table-column prop="description" label="描述" align="center" />
            <el-table-column label="状态" align="center">
              <template #default="{ row }">
                <span :style="{ color: row.status === '未邀请' ? 'green' : 'gray' }">
                  {{ row.status }}
                </span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :total="org_invite_list.length"
            :page-size="org_invite_list.length"
            layout="total"
            style="text-align: right; margin-top: 10px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmInviteMember">确认邀请</el-button>
          <el-button @click="inviteMemberDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 申请组织弹出框 -->
    <el-dialog
      v-model="applyOrgDialogVisible"
      :title="`申请加入 ${currentApplyOrg?.map(org => `【${org.org_name}】`).join(',')}`"
      width="30%"
      align-center="true"
    >
      <!-- <div>
        <p style="text-align: center">组织名称：{{ currentApplyOrg?.org_name }}</p>
        <p style="text-align: center">组织描述：{{ currentApplyOrg?.description }}</p>
        <p style="text-align: center">创建者：{{ currentApplyOrg?.created_by }}</p>
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmApplyOrg">确认申请</el-button>
          <el-button @click="applyOrgDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from "vue";
  import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
  import api from "../axios/api";
  import router from "../router";
  const local_student_id = localStorage.getItem("studentId"); // 本地学号

  //////////////////////////////////////////////////////////////////////////////////////////////////////////// 组织列表模块
  const dialogVisible = ref(false); // 新增组织对话框显示
  const organizationName = ref(""); // 组织名称 输入框
  const organizationDescription = ref(""); // 组织描述 输入框
  const number_2 = Number(local_student_id?.slice(0, 2)); // 学号前两位
  const years = ref([`20${number_2}`, `20${number_2 + 1}`, `20${number_2 + 2}`, `20${number_2 + 3}`]); // 学年
  const organizationYear = ref(""); // 组织学年 选择框
  const organizationTerm = ref(""); // 组织学期 选择框
  const isOrgLoading = ref(false); // 是否加载中
  const addOrganization = async () => {
    // 确认新增组织 按钮
    if (
      !organizationName.value ||
      !organizationDescription.value ||
      !organizationYear.value ||
      !organizationTerm.value
    ) {
      ElMessage.error("请填写完整信息");
      return;
    }
    try {
      const response = await api.addOrganization(
        localStorage.getItem("userId"),
        organizationName.value,
        organizationDescription.value,
        organizationYear.value,
        organizationTerm.value === "第一学期" ? 1 : 2
      );
      console.log(response);
      ElMessage.success("新增组织成功");
      dialogVisible.value = false;
      // 刷新组织列表
      await refreshOrganizationList();
    } catch (error) {
      ElMessage.error("新增组织失败");
      console.error("新增组织异常", error);
    }
  };
  const addOrgDialog = () => {
    // 新增组织 按钮
    dialogVisible.value = true;
  };
  const viewOrganization = (id: string) => {
    localStorage.setItem("orgData", JSON.stringify(organizations.value));
    // // 在新标签页中打开组织页面
    // window.open(`/MyOrgInfo/${id}`, '_blank');
    // 当前页面打开组织页面

    router.push(`/MyOrgInfo/${id}`);
  };

  interface org_item {
    // 组织列表
    org_id: string; // 组织ID
    org_name: string; // 组织名称
    org_description: string; // 组织描述
    created_at: string; // 创建时间
  }
  const organizations = ref<org_item[]>([]); // 组织列表
  const refreshOrganizationList = async () => {
    // 刷新组织列表
    isOrgLoading.value = true;
    const response = await api.getOrganizationList(localStorage.getItem("userId"));
    organizations.value = response.data;
    organizations.value.forEach((element: org_item) => {
      element.created_at = element.created_at.replace("T", " ");
    });
    isOrgLoading.value = false;
  };

  //////////////////////////////////////////////////////////////////////////////////////////////////////////// 搜索模块
  const searchQuery = ref(""); // 搜索关键词
  const searchType = ref("organization"); // 搜索类型
  const searchOrgKeywords = ref(""); // 搜索组织关键词
  const searchMemberKeywords = ref(""); // 搜索成员关键词
  const searchOrgResults = ref<search_org_item[]>([]); // 搜索组织结果
  const searchMemberResults = ref<search_member_item[]>([]); // 搜索成员结果
  const isSearchLoading = ref(false); // 是否搜索中
  const searchResults = computed(() => {
    // 搜索结果的绑定
    return searchType.value === "organization" ? searchOrgResults.value : searchMemberResults.value;
  });
  const inviteOrApply = (item: any) => {
    // 操作按钮 邀请或申请
    if (searchType.value === "member") {
      // 邀请成员
      currentInviteMember.value = [item];
      inviteMemberDialogVisible.value = true;
    } else {
      // 申请组织
      const tableData = JSON.parse(localStorage.getItem("tableData") || "[]");
      const course_year = item.course_year;
      const course_term = item.course_term;
      const has_table = tableData.some(
        (table_item: any) => table_item.year_term.year === course_year && table_item.year_term.semester === course_term
      );
      if (!has_table) {
        ElMessage.error({
          message: `请先获取${course_year}学年第${course_term}学期的课表, <a href="/MyCourse?y=${course_year}&s=${course_term}" target="_blank">点击获取</a>`,
          dangerouslyUseHTMLString: true,
          duration: 8000
        });
        return;
      }
      currentApplyOrg.value = [item];
      applyOrgDialogVisible.value = true;
    }
  };
  // 搜索组织 接口返回数据
  interface search_org_item {
    org_id: string; // 组织ID
    org_name: string; // 组织名称
    description: string; // 组织描述
    created_by: string; // 创建者
    course_year: string; // 组织学年
    course_term: string; // 组织学期
    updated_at: string; // 更新时间
  }
  // 搜索成员 接口返回数据
  interface search_member_item {
    user_id: string; // 用户ID
    username: string; // 学号
    email: string; // 邮箱
    updated_at: string; // 更新时间
  }
  const performSearch = async () => {
    // 搜索 按钮
    searchOrgResults.value = [];
    searchMemberResults.value = [];
    if (searchQuery.value === "") {
      ElMessage.error("请输入搜索关键词");
      return;
    }
    if (searchQuery.value.includes(" ") || searchQuery.value.includes("，") || searchQuery.value.includes("、")) {
      ElMessage.error("搜索关键词不能包含空格、中文逗号或中文顿号");
      return;
    }
    isSearchLoading.value = true;
    if (searchType.value === "organization") {
      searchOrgKeywords.value = searchQuery.value
        .split(",")
        .map((item: any) => `【${item}】`)
        .join(",");
      const response = await api.searchOrg(searchQuery.value);
      searchOrgResults.value = response.data;
    } else if (searchType.value === "member") {
      // 将搜索关键词拆分为数组，并添加【】
      searchMemberKeywords.value = searchQuery.value
        .split(",")
        .map((item: any) => `【${item}】`)
        .join(",");
      const response = await api.seachMember(searchQuery.value);
      searchMemberResults.value = response.data;
    }
    isSearchLoading.value = false;
  };

  const isRowSelectable = (row: any) => {
    // 检查行是否可选择
    if (searchType.value === "organization") {
      return row.created_by !== local_student_id;
    } else if (searchType.value === "member") {
      return row.username !== local_student_id;
    }
    return true;
  };

  const selectedSearchResults = ref<search_org_item[] | search_member_item[]>([]); // 选中搜索的搜索结果
  const isAnySearchSelected = computed(() => selectedSearchResults.value.length > 0); // 检查是否有选中的项

  const handleSearchSelectionChange = (selection: any[]) => {
    // 处理搜索选择变化
    selectedSearchResults.value = selection;
  };
  const inviteOrApplyAll = () => {
    // 全部邀请或申请
    console.log(selectedSearchResults.value);
    if (searchType.value === "member") {
      currentInviteMember.value = selectedSearchResults.value;
      inviteMemberDialogVisible.value = true;
    } else if (searchType.value === "organization") {
      const tableData = JSON.parse(localStorage.getItem("tableData") || "[]");
      let is_all_has_table = true;
      selectedSearchResults.value.forEach((item: any) => {
        const course_year = item.course_year;
        const course_term = item.course_term;
        const has_table = tableData.some(
          (table_item: any) =>
            table_item.year_term.year === course_year && table_item.year_term.semester === course_term
        );
        if (!has_table) {
          ElMessage.error({
            message: `请先获取${course_year}学年第${course_term}学期的课表, <a href="/MyCourse?y=${course_year}&s=${course_term}" target="_blank">点击获取</a>`,
            dangerouslyUseHTMLString: true,
            duration: 8000
          });
          is_all_has_table = false;
        }
      });
      if (!is_all_has_table) {
        return;
      }
      currentApplyOrg.value = selectedSearchResults.value;
      applyOrgDialogVisible.value = true;
    }
  };

  // 新增响应式变量
  const inviteMemberDialogVisible = ref(false); // 邀请成员弹出框
  const applyOrgDialogVisible = ref(false); // 申请组织弹出框
  const currentInviteMember = ref<search_member_item[] | any[]>([]); // 当前邀请成员
  const currentApplyOrg = ref<search_org_item | search_org_item[] | any[]>([]); // 当前申请组织
  const selectedInviteOrgs = ref<org_item[]>([]); // 选中邀请的组织

  // 处理组织选择变化
  const handleInviteOrgSelectionChange = (selection: org_item[]) => {
    selectedInviteOrgs.value = selection;
  };

  const getInvitationStatus = (row: any, member: any) => {
    // 获取邀请状态
    const is_invited = invitedOrgDict.value.some(
      invited => invited.org_id === row.org_id && invited.invitee_id === member.user_id
    );
    return is_invited ? "已邀请/已同意" : "未邀请";
  };

  // 获取已邀请的被邀请人和组织
  const invitedOrgDict = computed(() => {
    const data = msgs.value
      .filter((msg: any) => msg.type === "我邀请Ta加入我" && msg.status !== "rejected")
      .map((msg: any) => {
        return {
          invitee_id: msg.user_id,
          org_id: msg.org_id
        };
      });
    console.log(data);
    return data;
  });

  const org_invite_list = computed(() => {
    // 组织邀请列表 organizations增加user_id、status
    const data = [];
    for (const member of currentInviteMember.value) {
      for (const org of organizations.value) {
        const status = getInvitationStatus(org, member);
        const username = member.username;
        const user_id = member.user_id;
        data.push({ ...org, username, status, user_id });
      }
    }
    return data;
  });

  // 检查组织是否未被邀请
  const isOrgSelectable = (row: any) => {
    return !org_invite_list.value.some(org => org.user_id === row.user_id && org.status === "已邀请");
  };

  // 确认邀请成员
  const confirmInviteMember = async () => {
    ElMessageBox.confirm("确定要邀请吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      if (selectedInviteOrgs.value.length === 0) {
        ElMessage.error("请选择要邀请的组织");
        return;
      }
      const loading = ElLoading.service({
        lock: true,
        text: "邀请中...",
        background: "rgba(0, 0, 0, 0.7)"
      });
      console.log(selectedInviteOrgs.value);
      console.log(currentInviteMember.value);

      // 去重
      const org_ids = [...new Set(selectedInviteOrgs.value.map((org: any) => org.org_id))];
      const invitee_ids = [...new Set(currentInviteMember.value.map((member: any) => member.user_id))];
      const inviter_id = localStorage.getItem("userId");
      try {
        await api.inviteMember(org_ids, inviter_id, invitee_ids);
        ElMessage.success("邀请发送成功");
        inviteMemberDialogVisible.value = false;
        selectedInviteOrgs.value = [];
        await refreshMsgList("未回应"); // 刷新消息列表
      } catch (error) {
        ElMessage.error("邀请发送失败");
        console.error("邀请发送异常", error);
      } finally {
        loading.close();
      }
    });
  };

  // 确认申请组织
  const confirmApplyOrg = async () => {
    const loading = ElLoading.service({
      lock: true,
      text: "申请中...",
      background: "rgba(0, 0, 0, 0.7)"
    });
    console.log(currentApplyOrg.value);
    const org_ids = currentApplyOrg.value.map((org: any) => org.org_id);
    const user_id = localStorage.getItem("userId");
    try {
      await api.requestJoinOrg(user_id, org_ids);
      ElMessage.success("申请发送成功");
      applyOrgDialogVisible.value = false;
      await refreshMsgList("未回应"); // 刷新消息列表
    } catch (error) {
      ElMessage.error("申请发送失败");
      console.error("申请发送异常", error);
    } finally {
      loading.close();
    }
  };
  //////////////////////////////////////////////////////////////////////////////////////////////////////////// 通知列表模块
  // 通知类型
  const msgStatus = ref("待处理"); // 通知类型 选择框
  const isAnyMsgSelected = computed(() => selectedMsgResults.value.length > 0); // 检查是否有选中的项
  const selectedMsgResults = ref<any[]>([]); // 选中消息结果
  const showMsgs = ref([]); // 显示的消息
  const msgs = ref([]); // 消息列表
  const isMsgLoading = ref(false); // 是否加载中
  // 获取已申请的组织ID列表
  const appliedOrgIds = computed(() => {
    return msgs.value
      .filter((msg: any) => msg.type === "我申请加入Ta" && msg.status !== "rejected")
      .map((msg: any) => msg.org_id);
  });
  // 获取已被邀请的组织ID列表
  const invitedOrgIds = computed(() => {
    return msgs.value
      .filter((msg: any) => msg.type === "Ta邀请我加入" && msg.status !== "rejected")
      .map((msg: any) => msg.org_id);
  });
  const handleMsgStatusChange = (msg_status: string) => {
    const status = msg_status || msgStatus.value;
    // 通知类型 改变, 刷新消息列表
    msgStatus.value = status;
    if (status === "未回应") {
      showMsgs.value = msgs.value.filter(
        (msg: any) => (msg.type === "我邀请Ta加入我" || msg.type === "我申请加入Ta") && msg.status === "pending"
      );
    } else if (status === "待处理") {
      showMsgs.value = msgs.value.filter(
        (msg: any) => (msg.type === "Ta申请加入我" || msg.type === "Ta邀请我加入") && msg.status === "pending"
      );
    } else {
      showMsgs.value = msgs.value.filter((msg: any) => msg.status !== "pending");
    }
    console.log(status, showMsgs.value);
  };

  const handleMsgSelectionChange = (selection: any[]) => {
    // 处理消息选择变化
    selectedMsgResults.value = selection;
  };
  // 设置消息状态
  const setMsgStatus = async (msg: any, status: string) => {
    // 设置消息状态
    console.log(msg, status);
    // return
    if (msg.type.includes("邀请")) {
      // 邀请
      // 检查是否获取了该学年学期的课表
      const tableData = JSON.parse(localStorage.getItem("tableData") || "[]");
      const course_year = msg.org_info.course_year;
      const course_term = msg.org_info.course_term;
      const has_table = tableData.some(
        (table_item: any) => table_item.year_term.year === course_year && table_item.year_term.semester === course_term
      );
      if (!has_table) {
        ElMessage.error({
          message: `请先获取${course_year}学年第${course_term}学期的课表, <a href="/MyCourse?y=${course_year}&s=${course_term}" target="_blank">点击获取</a>`,
          dangerouslyUseHTMLString: true,
          duration: 8000
        });
        return;
      }

      try {
        await api.setInvitationStatus([msg.msg_id], status);
        ElMessage.success(`${status === "approved" ? "同意" : "拒绝"}邀请成功`);
        await refreshMsgList("已处理"); // 刷新消息列表
      } catch (error) {
        ElMessage.error(`${status === "approved" ? "同意" : "拒绝"}邀请失败`);
        console.error(`${status === "approved" ? "同意" : "拒绝"}邀请异常`, error);
      }
    } else if (msg.type.includes("申请")) {
      // 申请
      try {
        await api.setRequestStatus([msg.msg_id], status);
        ElMessage.success(`${status === "approved" ? "同意" : "拒绝"}申请成功`);
        await refreshMsgList("已处理"); // 刷新消息列表
      } catch (error) {
        ElMessage.error(`${status === "approved" ? "同意" : "拒绝"}申请失败`);
        console.error(`${status === "approved" ? "同意" : "拒绝"}申请异常`, error);
      }
    }
  };

  // 全部处理
  const setAllMsgStatus = async (status: string) => {
    ElMessageBox.confirm(`确定要全部${status === "approved" ? "同意" : "拒绝"}吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      const loading = ElLoading.service({
        lock: true,
        text: "处理中...",
        background: "rgba(0, 0, 0, 0.7)"
      });
      // 检查邀请的组织是否获取了该学年学期的课表
      const tableData = JSON.parse(localStorage.getItem("tableData") || "[]");
      let is_all_has_table = true;
      selectedMsgResults.value.forEach((msg: any) => {
        if (!msg.type.includes("邀请")) {
          return;
        }
        const course_year = msg.org_info.course_year;
        const course_term = msg.org_info.course_term;
        const has_table = tableData.some(
          (table_item: any) =>
            table_item.year_term.year === course_year && table_item.year_term.semester === course_term
        );
        if (!has_table) {
          ElMessage.error({
            message: `请先获取${course_year}学年第${course_term}学期的课表, <a href="/MyCourse?y=${course_year}&s=${course_term}" target="_blank">点击获取</a>`,
            dangerouslyUseHTMLString: true,
            duration: 8000
          });
          is_all_has_table = false;
        }
      });
      if (!is_all_has_table) {
        loading.close();
        return;
      }

      const msg_ids = selectedMsgResults.value.map((msg: any) => {
        return { msg_id: msg.msg_id, msg_type: msg.type };
      });
      console.log(msg_ids);

      const invitation_ids = msg_ids.filter((msg: any) => msg.msg_type.includes("邀请")).map((msg: any) => msg.msg_id);
      const request_ids = msg_ids.filter((msg: any) => msg.msg_type.includes("申请")).map((msg: any) => msg.msg_id);
      try {
        if (invitation_ids.length > 0) {
          await api.setInvitationStatus(invitation_ids, status);
        }
        if (request_ids.length > 0) {
          await api.setRequestStatus(request_ids, status);
        }
        ElMessage.success(`全部${status === "approved" ? "同意" : "拒绝"}成功`);
        await refreshMsgList("已处理"); // 刷新消息列表
      } catch (error) {
        ElMessage.error(`全部${status === "approved" ? "同意" : "拒绝"}失败`);
        console.error(`全部${status === "approved" ? "同意" : "拒绝"}异常`, error);
      } finally {
        loading.close();
      }
    });
  };

  // 撤回
  const withdraw = async (msg: any) => {
    ElMessageBox.confirm("确定要撤回吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      // 撤回
      console.log(msg);
      const msg_ids = [msg.msg_id];
      const type = msg.type.includes("邀请") ? "invitation" : "request";
      const loading = ElLoading.service({
        lock: true,
        text: "撤回中...",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        await api.withdrawMsg(msg_ids, type);
        ElMessage.success("撤回成功");
        await refreshMsgList("未回应"); // 刷新消息列表
      } catch (error) {
        ElMessage.error("撤回失败");
        console.error("撤回异常", error);
      } finally {
        loading.close();
      }
    });
  };

  // 全部撤回
  const withdrawAll = async () => {
    // 全部撤回
    ElMessageBox.confirm("确定要全部撤回吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      // selectedMsgResults.value.forEach(msg => withdraw(msg))
      const loading = ElLoading.service({
        lock: true,
        text: "撤回中...",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const msg_ids_invitation = selectedMsgResults.value
        .filter((msg: any) => msg.type.includes("邀请"))
        .map((msg: any) => msg.msg_id);
      const msg_ids_request = selectedMsgResults.value
        .filter((msg: any) => msg.type.includes("申请"))
        .map((msg: any) => msg.msg_id);
      try {
        if (msg_ids_invitation.length > 0) {
          await api.withdrawMsg(msg_ids_invitation, "invitation");
        }
        if (msg_ids_request.length > 0) {
          await api.withdrawMsg(msg_ids_request, "request");
        }
        ElMessage.success("全部撤回成功");
        await refreshMsgList("未回应"); // 刷新消息列表
      } catch (error) {
        ElMessage.error("全部撤回失败");
        console.error("全部撤回异常", error);
      } finally {
        loading.close();
      }
    });
  };

  // 刷新消息列表
  const refreshMsgList = async (msg_status: string) => {
    isMsgLoading.value = true;
    const response = await api.getMsgList(localStorage.getItem("userId"));
    msgs.value = response.data;
    msgs.value.forEach((element: any) => {
      element.updatetime = element.updatetime.replace("T", " ");
    });
    console.log(msgs.value);
    isMsgLoading.value = false;
    handleMsgStatusChange(msg_status); // 刷新消息列表
  };

  // 挂载
  onMounted(async () => {
    await refreshOrganizationList(); // 刷新组织列表
    await refreshMsgList("待处理"); // 刷新消息列表
  });
</script>

<style lang="less" scoped>
  .organization-module {
    display: flex;
    flex-direction: column;
    gap: 20px;
    // padding: 20px;

    .top-sections {
      display: flex;
      gap: 20px;
    }

    .organization-section {
      flex: 2;
    }

    .notice-section {
      flex: 3;
    }

    .section {
      // padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      h2 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    .organization-table,
    .member-table {
      margin-top: 16px;
    }

    .status-tag,
    .msg-status {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
    }

    .el-button {
      margin: 2px 4px;
    }

    .search-section {
      // margin-top: 20px;
      // padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .search-controls {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .search-input {
      flex: 1;
    }

    .search-type {
      display: flex;
    }
  }
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .spin-icon {
    animation: spin 1s linear infinite;
  }

  .popover-content {
    display: flex;
    flex-direction: column;
    gap: 8px; /* 调整行间距 */
  }

  .popover-content p {
    display: flex;
    align-items: center;
    margin: 0; /* 去除默认的段落间距 */
  }

  .popover-content .label {
    display: inline-block;
    width: auto; /* 固定宽度，确保所有标签宽度一致 */
    // text-align-last: justify; /* 让标签文本两端对齐 */
    text-align: right; /* 右对齐 */
    margin-right: 8px; /* 标签和内容之间的间距 */
  }
</style>
